<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <!-- 自定义指令来实现按钮级别的权限控制 -->
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('export')" -->

          <!-- v-allow是我们自己定义的指令。
          他的作用是：只有当vuex中保存的权限有export时，这个元素才被可见 -->
          <el-button
            v-allow="'export'"
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="hAdd"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="pageList.size"
            :current-page.sync="pageList.page"
            :page-sizes="[1,2, 4, 6, 8, 10]"
            :total="total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="doSizeChange"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <empDialog v-if="showDialog" @close="showDialog=false" @success="hsuccess" />
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="showDialogRole">
      <assign-role v-if="showDialogRole" :employee-id="curId" @close="hClose" @success="hSuccessRole" />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployees, delEmployees } from '@/api/employees.js'
import { formatExcelDate } from '@/utils'
import EmployeeEnum from '@/constant/employees'
const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
import empDialog from './empDialog'
import AssignRole from './AssignRole.vue'
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      // 角色列表参数,也是页面列表的默认参数
      pageList: {
        page: 1,
        size: 10
      },
      // 分配角色弹窗
      showDialogRole: false,
      // 添加弹窗
      showDialog: false,
      // 表格数据
      list: [],
      // 总页数
      total: 0,
      // 正则校验
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      curId: ''
    }
  },
  created() {
    // 请求表格数据
    this.loadEmployees()
  },
  methods: {
    // 关闭分配页弹窗
    hClose() {
      this.showDialogRole = false
    },
    //
    hSuccessRole() {
      this.showDialogRole = false
    },
    // 分配权限
    hAssignRole(id) {
      console.log(id)
      this.showDialogRole = true
      this.curId = id
    },
    //  size发生变化
    doSizeChange(size) {
      console.log('页码发生变化', size)
      // 修改每页数量
      this.pageList.size = size
      this.pageList.page = 1 // 每页数量变化,页码恢复到1
      // 刷新列表
      this.loadEmployees()
    },
    // 页面发生变化
    hCurrentChange(page) {
      console.log('页面发生变化', page)
      // 更新页面
      this.pageList.page = page
      this.loadEmployees()
    },
    // 删除模块
    async doDel(id) {
      const res = await delEmployees(id)
      console.log(res)
      this.$message.success('删除成功')
      // 如果为最后一条数据,则页码要减1
      if (this.list.length === 1) {
        this.pageList.page--
        this.pageList.page = Math.max(1, this.pageList.page)
      }
      this.loadEmployees()
    },
    hDel(id) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
        this.loadEmployees()
      }).catch(() => {

      })
    },
    // 新增员工
    hAdd() {
      this.showDialog = true
    },
    // 枚举
    // formatEmployment(num) {
    //   const item = EmployeeEnum.hireType.find(item => item.id === num)
    //   if (item) {
    //     return item.value
    //   } else {
    //     return '未知'
    //   }
    // },
    formatEmployment(id) {
      return hireType[id] || '未知'
    },
    // 请求表格数据
    async loadEmployees() {
      const res = await getEmployees(this.pageList)
      console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 新增
    hsuccess() {
      this.showDialog = false
      this.total++
      // 最后一页
      this.pageList.page = Math.ceil(this.total / this.pageList.size)
      this.loadEmployees()
    },
    // 导出
    transformData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const header = Object.keys(rows[0])
      const zhHeader = header.map(key => map[key])
      const data = rows.map(item => {
        return header.map(key => {
          if (key === 'formOfEmployment') {
            return hireType[item[key]]
          } else if (key === 'correctionTime' || key === 'timeOfEntry') {
            return Date(formatExcelDate(item[key]))
          } else {
            return item[key]
          }
        })
      })
      return {
        header: zhHeader, data
      }
    },
    // 导出
    hExportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发请求
        const res = await getEmployees(this.pageList)
        console.log('要导出的数据', res.data.rows)
        // excel表示导入的模块对象
        console.log(excel)
        const { header, data } = this.transformData(res.data.rows)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }
  }
}
</script>
